package org.jackysoft.config;

import java.beans.PropertyVetoException;
import java.io.IOException;

import javax.sql.DataSource;

import org.apache.ibatis.session.ExecutorType;
import org.jackysoft.bean.define.ActionBeanPostProcessor;
import org.jackysoft.bean.define.TransactionNames;
import org.jackysoft.db.DataSourceFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
public class StandardConfig {

	final static Logger logger = LoggerFactory
			.getLogger(StandardConfig.class);

	@Autowired
	ContextConfig context;
	
	@Bean
	public static ActionBeanPostProcessor actionBeanPostProcessor() {
		ActionBeanPostProcessor apt = new ActionBeanPostProcessor();

		return apt;
	}

	@Bean(name = "nmds")
	public DataSource nmds() {
		String jdbcnm = "jdbc-nm.properties";
		return DataSourceFactory.buildDataSource(jdbcnm);
	}
	
	@Bean(name=TransactionNames.IBATIS_TRANSACTION)
	public DataSourceTransactionManager ibatisTransactionManager(){
		DataSourceTransactionManager bean = new DataSourceTransactionManager();
		bean.setDataSource(nmds());
		return bean;
	}
	
	@Bean
	public SqlSessionFactoryBean sqlSessionFactory() throws IOException,
			PropertyVetoException {

		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		String path  = "classpath*:org/jackysoft/mapper/*Mapper.xml";
		PathMatchingResourcePatternResolver prp = new PathMatchingResourcePatternResolver();
		Resource[] mapperLocations = prp.getResources(path);		
		bean.setDataSource(nmds());
		bean.setTypeAliasesPackage(context.typeAliasesPackage());
		bean.setMapperLocations(mapperLocations);        	
		bean.setTypeHandlersPackage(context.typeHandlerPackage());		
		return bean;

	}

	@Bean
	public SqlSessionTemplate sqlSession() throws Exception {
		SqlSessionTemplate session = new SqlSessionTemplate(sqlSessionFactory()
				.getObject(),ExecutorType.BATCH);

		return session;
	}

}
